// pages/home/home.js
const mqtt = require('../../utils/mqtt.js')
const crypto = require('../../utils/hex_hmac_sha1.js')
const common = require('../common.js')
const queue = require('../queue.js')

const db = wx.cloud.database()
const productsCollection = db.collection('products')
const docId = 'sensorThreshold'
Page({
  data: {
    Temperature: 0, // AD传感器   温度
    Humidity: 0, // 湿度
    Flame: 0, // 火焰传感器
    Combustible: 0, // 可燃气体传感器
    Potentiometer: 0, // 电位器
    Light: 0, // 光照
    Smoke: 0, // 烟雾传感器
    Ultrasonic: 0, // 超声波检测距离
    Infrared: 0, // 红外传感器
    Photoelectric: 0, // 光电传感器 
    Touch: 0, // 触摸按建
    Raindrop: 0, // 雨滴检测

    Temperature_power: 0, // 电源电量
    Flame_power: 0,
    Combustible_power: 0,
    Potentiometer_power: 0,
    Light_power: 0,
    Smoke_power: 0,
    Ultrasonic_power: 0,
    Infrared_power: 0,
    Photoelectric_power: 0,
    Touch_power: 0,
    Raindrop_power: 0,

    Fan_status: '',
    Fan_power: '',
    Buzzer_status: '',
    Buzzer_power: '',
    Relay_status: '',
    Relay_power: '',

    Temperature_upper_threshold: 0,
    Temperature_lower_threshold: 0,
    Humidity_upper_threshold: 0,
    Humidity_lower_threshold: 0,
    Flame_upper_threshold: 0,
    Flame_lower_threshold: 0,
    Smoke_upper_threshold: 0,
    Smoke_lower_threshold: 0,
    Raindrop_upper_threshold: 0,
    Raindrop_lower_threshold: 0,
    Combustible_upper_threshold: 0,
    Combustible_lower_threshold: 0,
    Light_upper_threshold: 0,
    Light_lower_threshold: 0,
    Potentiometer_upper_threshold: 0,
    Potentiometer_lower_threshold: 0,

    active: 0, // 顶部标签的初始值为第一页
    activeNames: ['1'], // 折叠面板必需的参数
  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  onCollapseChange(event) { // 折叠面板的触发函数
    this.setData({
      activeNames: event.detail,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   * 页面加载完成,一个页面只加载一次
   * 加载完成之后初始化数据库，并将数据中的内容加载到页面中
   */
  onLoad(event) {
    productsCollection.doc(docId).get({
      success: res => {
        common.set_message_TemperatureUpper(res.data.Temperature.Upper)
        common.set_message_TemperatureLower(res.data.Temperature.Lower)
        common.set_message_HumidityUpper(res.data.Humidity.Upper)
        common.set_message_HumidityLower(res.data.Humidity.Lower)
        common.set_message_FlameUpper(res.data.Flame.Upper)
        common.set_message_FlameLower(res.data.Flame.Lower)
        common.set_message_SmokeUpper(res.data.Smoke.Upper)
        common.set_message_SmokeLower(res.data.Smoke.Lower)
        common.set_message_RaindropUpper(res.data.Raindrop.Upper)
        common.set_message_RaindropLower(res.data.Raindrop.Lower)
        common.set_message_CombustibleUpper(res.data.Combustible.Upper)
        common.set_message_CombustibleLower(res.data.Combustible.Lower)
        common.set_message_LightUpper(res.data.Light.Upper)
        common.set_message_LightLower(res.data.Light.Lower)
        common.set_message_PotentiometerUpper(res.data.Potentiometer.Upper)
        common.set_message_PotentiometerLower(res.data.Potentiometer.Lower)
        this.setData({
          Temperature_upper_threshold: res.data.Temperature.Upper,
          Temperature_lower_threshold: res.data.Temperature.Lower,
          Humidity_upper_threshold: res.data.Humidity.Upper,
          Humidity_lower_threshold: res.data.Humidity.Lower,
          Flame_upper_threshold: res.data.Flame.Upper,
          Flame_lower_threshold: res.data.Flame.Lower,
          Smoke_upper_threshold: res.data.Smoke.Upper,
          Smoke_lower_threshold: res.data.Smoke.Lower,
          Raindrop_upper_threshold: res.data.Raindrop.Upper,
          Raindrop_lower_threshold: res.data.Raindrop.Lower,
          Combustible_upper_threshold: res.data.Combustible.Upper,
          Combustible_lower_threshold: res.data.Combustible.Lower,
          Light_upper_threshold: res.data.Light.Upper,
          Light_lower_threshold: res.data.Light.Lower,
          Potentiometer_upper_threshold: res.data.Potentiometer.Upper,
          Potentiometer_lower_threshold: res.data.Potentiometer.Lower,
        })
      }
    })
    this.doUpdateControlStatus()
    this.doConnect()
  },
  doUpdateControlStatus: function () {
    var that = this
    setInterval(function () {
      that.setData({
        Fan_status: common.get_message_Fan_Status(),
        Buzzer_status: common.get_message_Buzzer_Status(),
        Relay_status: common.get_message_Relay_Status(),

        Fan_power: common.get_message_Fan_Power(),
        Buzzer_power: common.get_message_Buzzer_Power(),
        Relay_power: common.get_message_Relay_Power(),
      })
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面隐藏
   * 页面被隐藏后，将数据库中的内容进行更新
   */
  onHide: function () {
    console.log("页面被隐藏")
    productsCollection.doc(docId).update({
      data: {
        Temperature: {
          Upper: common.get_message_TemperatureUpper(),
          Lower: common.get_message_TemperatureLower(),
        },
        Humidity: {
          Upper: common.get_message_HumidityUpper(),
          Lower: common.get_message_HumidityLower(),
        },
        Flame: {
          Upper: common.get_message_FlameUpper(),
          Lower: common.get_message_FlameLower(),
        },
        Smoke: {
          Upper: common.get_message_SmokeUpper(),
          Lower: common.get_message_SmokeLower(),
        },
        Raindrop: {
          Upper: common.get_message_RaindropUpper(),
          Lower: common.get_message_RaindropLower(),
        },
        Combustible: {
          Upper: common.get_message_CombustibleUpper(),
          Lower: common.get_message_CombustibleLower(),
        },
        Light: {
          Upper: common.get_message_LightUpper(),
          Lower: common.get_message_LightLower(),
        },
        Potentiometer: {
          Upper: common.get_message_PotentiometerUpper(),
          Lower: common.get_message_PotentiometerLower(),
        }
      }
    }).then(res => {
      console.log(res)
    })
  },
  /****************************************** 温湿度传感器 —— 温度 ******************************************/
  onTemperatureUpperChange(event) {
    common.set_message_TemperatureUpper(Number(event.detail));
  },
  onTemperatureLowerChange(event) {
    common.set_message_TemperatureLower(Number(event.detail));
  },

  /****************************************** 温湿度传感器 —— 湿度 ******************************************/
  onHumidityUpperChange(event) {
    common.set_message_HumidityUpper(Number(event.detail));
  },
  onHumidityLowerChange(event) {
    common.set_message_HumidityLower(Number(event.detail));
  },

  /****************************************** 火焰传感器 ******************************************/
  onFlameUpperChange(event) {
    common.set_message_FlameUpper(Number(event.detail))
  },
  onFlameLowerChange(event) {
    common.set_message_FlameLower(Number(event.detail))
  },

  /****************************************** 烟雾传感器 ******************************************/
  onSmokeUpperChange(event) {
    common.set_message_SmokeUpper(Number(event.detail))
  },
  onSmokeLowerChange(event) {
    common.set_message_SmokeLower(Number(event.detail))
  },

  /****************************************** 雨滴传感器 ******************************************/
  onRaindropUpperChange(event) {
    common.set_message_RaindropUpper(Number(event.detail))
  },
  onRaindropLowerChange(event) {
    common.set_message_RaindropLower(Number(event.detail))
  },

  /****************************************** 可燃气体传感器 ******************************************/
  onCombustibleUpperChange(event) {
    common.set_message_CombustibleUpper(Number(event.detail))
  },
  onCombustibleLowerChange(event) {
    common.set_message_CombustibleLower(Number(event.detail))
  },

  /****************************************** 光照传感器 ******************************************/
  onLightUpperChange(event) {
    common.set_message_LightUpper(Number(event.detail))
  },
  onLightLowerChange(event) {
    common.set_message_LightLower(Number(event.detail))
  },

  /****************************************** 电位器传感器 ******************************************/
  onPotentiometerUpperChange(event) {
    common.set_message_PotentiometerUpper(Number(event.detail))
  },
  onPotentiometerLowerChange(event) {
    common.set_message_PotentiometerLower(Number(event.detail))
  },

  switch_SensorNetwork(json) {
    switch (json) {
      case "ZigBee": {
        common.set_message_Fan_Network('ZigBee');
        common.set_message_Buzzer_Network('ZigBee');
        common.set_message_Relay_Network('ZigBee');
      }
      break;
    case "WiFi": {
      common.set_message_Fan_Network('WiFi');
      common.set_message_Buzzer_Network('WiFi');
      common.set_message_Relay_Network('WiFi');
    }
    break;
    case "IPV6": {
      common.set_message_Fan_Network('IPV6');
      common.set_message_Buzzer_Network('IPV6');
      common.set_message_Relay_Network('IPV6');
    }
    break;
    case "BlueTooth": {
      common.set_message_Fan_Network('BlueTooth');
      common.set_message_Buzzer_Network('BlueTooth');
      common.set_message_Relay_Network('BlueTooth');
    }
    break;

    default:
      break;
    }
  },
  doConnect() {
    var that = this;
    const options = this.aliyun_initMqttOptions(common.get_message_Aliyun());
    let aliyun_serverAddess = `wxs://${common.get_message_Aliyun_ProductKey()}.iot-as-mqtt.${common.get_message_Aliyun_RegionId()}.aliyuncs.com`
    var client = 0

    client = mqtt.connect(aliyun_serverAddess, options)
    client.on('connect', function (err) {
      if (!err) {
        console.log('连接服务器成功')
      } else {
        console.log('连接服务器失败')
      }
    })
    common.set_message_MQTT_Client(client)
    let topic = `/${common.get_message_Aliyun_ProductKey()}/${common.get_message_Aliyun_DeviceName()}/user/Up_sensorData`
    client.subscribe(topic, {
      qos: 0
    }, function (err) {
      if (!err) {
        console.log('订阅成功')
      } else {
        console.log('订阅失败')
      }
    })

    client.on('message', function (topic, message, packet) {
      let payloadStr = packet.payload.toString()
      console.log('收到消息: ' + payloadStr)
      var json = JSON.parse(payloadStr);
      switch (json.SensorType) {
        case "Touch": {
          if (json.Data == '1') {
            that.setData({
              Touch: "按下"
            })
          } else if (json.Data == '0') {
            that.setData({
              Touch: "抬起"
            })
          }
          that.setData({
            Touch_power: json.Power,
          })
        }
        break;
      case "Photoelectric": {
        if (json.Data == '1') {
          that.setData({
            Photoelectric: "开门"
          })
        } else if (json.Data == '0') {
          that.setData({
            Photoelectric: "关门"
          })
        }
        that.setData({
          Photoelectric_power: json.Power,
        })
      }
      break;
      case "Buzzer": {
        that.switch_SensorNetwork(json.NetType) // 判断是什么网络类型，并设置相关的环境变量
        if (json.Data == '1') {
          common.set_message_Buzzer_Status('开')
        } else if (json.Data == '0') {
          common.set_message_Buzzer_Status('关')
        }
        common.set_message_Buzzer_Power(json.Power)
      }
      break;
      case "Fan": {
        that.switch_SensorNetwork(json.NetType) // 判断是什么网络类型，并设置相关的环境变量
        if (json.Data == '1') {
          common.set_message_Fan_Status('开')
        } else if (json.Data == '0') {
          common.set_message_Fan_Status('关')
        }
        common.set_message_Fan_Power(json.Power)
      }
      break;
      case "Relay": {
        that.switch_SensorNetwork(json.NetType) // 判断是什么网络类型，并设置相关的环境变量
        if (json.Data == '1') {
          common.set_message_Relay_Status('开')
        } else if (json.Data == '0') {
          common.set_message_Relay_Status('关')
        }
        common.set_message_Relay_Power(json.Power)
      }
      break;
      case "Infrared": {
        if (json.Data == '1') {
          that.setData({
            Infrared: "有人"
          })
        } else if (json.Data == '0') {
          that.setData({
            Infrared: "无人"
          })
        }
        that.setData({
          Infrared_power: json.Power,
        })
      }
      break;
      case "Flame": {
        let data = json.Data

        if (data < common.get_message_FlameLower()) {
          console.log("超出下限阈值")
        } else if (data > common.get_message_FlameUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Flame_power: json.Power,
          Flame: json.Data
        })
      }
      break;
      case "Combustible": { // 可燃气体传感器
        let data = json.Data

        if (data < common.get_message_FlameLower()) {
          console.log("超出下限阈值")
        } else if (data > common.get_message_FlameUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Combustible_power: json.Power,
          Combustible: json.Data
        })
      }
      break;
      case "Potentiometer": { // 电压
        let data = json.Data
        if (data < common.get_message_PotentiometerLower()) {
          console.log("超出下限阈值 + " + data)
          that.Fan_status_ONOrOFF(0)
        } else if (data > common.get_message_PotentiometerUpper()) {
          console.log("超出上限阈值 + " + data + "upper: " + common.get_message_PotentiometerUpper())
          that.Fan_status_ONOrOFF(1)

        }
        that.setData({
          Potentiometer_power: json.Power,
          Potentiometer: json.Data
        })
      }
      break;
      case "Light": {
        let data = json.Data

        if (data < common.get_message_LightLower()) {
          console.log("超出下限阈值")
        } else if (data > common.get_message_LightUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Light_power: json.Power,
          Light: json.Data
        })
      }
      break;
      case "Smoke": {
        let data = json.Data

        if (data < common.get_message_SmokeLower()) {
          console.log("超出下限阈值")
        } else if (data > common.get_message_SmokeUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Smoke_power: json.Power,
          Smoke: json.Data
        })
      }
      break;
      case "Raindrop": {
        let data = json.Data
        

        if (data < common.get_message_RaindropLower()) {
          console.log("超出下限阈值")
        } else if (data > common.get_message_RaindropUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Raindrop_power: json.Power,
          Raindrop: json.Data
        })
      }
      break;
      case "TempAndHumi": {
        let Temp = json.Temp
        
        if (Temp < common.get_message_TemperatureLower()) {
          console.log("超出下限阈值")
        } else if (Temp > common.get_message_TemperatureUpper()) {
          console.log("超出上限阈值")
        }

        let Humi = json.Humi
        if (Humi < common.get_message_HumidityLower()) {
          console.log("超出下限阈值")
        } else if (Humi > common.get_message_HumidityUpper()) {
          console.log("超出上限阈值")
        }
        that.setData({
          Temperature_power: json.Power,
          Temperature: json.Temp,
          Humidity: json.Humi
        })
      }
      break;
      case "Ultrasonic": {
        
        that.setData({
          Ultrasonic_power: json.Power,
          Ultrasonic: json.Data
        })
      }
      break;
      default:
        break;
      }
    })
  },

  // 风扇开关的响应函数
  Fan_status_ONOrOFF(value) {
    let client = common.get_message_MQTT_Client()
    let topic = `/${common.get_message_Aliyun_ProductKey()}/${common.get_message_Aliyun_DeviceName()}/user/Down_controlCmd`;
    if (value == 1) {
      let jsonStr = `{"Network":"${common.get_message_Fan_Network()}","Sensor":"Fan","Data":1}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 开风扇!')
        }
      })
    } else if (value == 0) {
      let jsonStr = `{"Network":"${common.get_message_Fan_Network()}","Sensor":"Fan","Data":0}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 关风扇!')
        }
      })
    }
  },
  onFanChange: function (sw) {
    if (sw.detail.value) {
      this.Fan_status_ONOrOFF(1)
    } else {
      this.Fan_status_ONOrOFF(0)
    }
  },

  // 报警器开关的响应函数
  Beep_status_ONOrOFF(value) {
    let client = common.get_message_MQTT_Client()
    let topic = `/${common.get_message_Aliyun_ProductKey()}/${common.get_message_Aliyun_DeviceName()}/user/Down_controlCmd`;
    if (value == 1) {
      let jsonStr = `{"Network":"${common.get_message_Buzzer_Network()}","Sensor":"Buzzer","Data":1}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 开蜂鸣器!')
        }
      })
    } else if (value == 0) {
      let jsonStr = `{"Network":"${common.get_message_Buzzer_Network()}","Sensor":"Buzzer","Data":0}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 关蜂鸣器!')
        }
      })
    }
  },
  onBeepChange: function (sw) {
    if (sw.detail.value) {
      this.Beep_status_ONOrOFF(1)
    } else {
      this.Beep_status_ONOrOFF(0)
    }
  },
  // 继电器开关的响应函数
  Relay_status_ONOrOFF(value) {
    let client = common.get_message_MQTT_Client()
    let topic = `/${common.get_message_Aliyun_ProductKey()}/${common.get_message_Aliyun_DeviceName()}/user/Down_controlCmd`;
    if (value == 1) {
      let jsonStr = `{"Network":"${common.get_message_Relay_Network()}","Sensor":"Relay","Data":1}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 开继电器!')
        }
      })
    } else if (value == 0) {
      let jsonStr = `{"Network":"${common.get_message_Relay_Network()}","Sensor":"Relay","Data":0}`
      client.publish(topic, jsonStr, function (err) {
        if (!err) {
          console.log('成功下发命令 关继电器!')
        }
      })
    }
  },
  onRelayChange: function (sw) {
    if (sw.detail.value) {
      this.Relay_status_ONOrOFF(1)
    } else {
      this.Relay_status_ONOrOFF(0)
    }
  },
  //IoT平台mqtt连接参数初始化
  aliyun_initMqttOptions(Aliyun_deviceConfig) {
    const params = {
      productKey: Aliyun_deviceConfig.productKey,
      deviceName: Aliyun_deviceConfig.deviceName,
      timestamp: Date.now(),
      clientId: Math.random().toString(36).substr(2),
    }

    // CONNECT参数
    const options = {
      keepalive: 60, // 60s
      clean: true, // cleanSession不保持持久会话
      protocolVersion: 4 // MQTT v3.1.1
    }

    //1.生成clientId，username，password
    options.password = this.signHmacSha1(params, Aliyun_deviceConfig.deviceSecret);
    options.clientId = `${params.clientId}|securemode=2,signmethod=hmacsha1,timestamp=${params.timestamp}|`;
    options.username = `${params.deviceName}&${params.productKey}`;

    return options;
  },

  //  生成基于HmacSha1的password
  // 参考文档：https://help.aliyun.com/document_detail/73742.html?#h2-url-1
  signHmacSha1(params, deviceSecret) {
    let keys = Object.keys(params).sort();
    // 按字典序排序
    keys = keys.sort();
    const list = [];
    keys.map((key) => {
      list.push(`${key}${params[key]}`);
    });
    const contentStr = list.join('');
    return crypto.hex_hmac_sha1(deviceSecret, contentStr);
  },

  // 设备下线 按钮点击事件
  offline: function () {
    let client = common.get_message__MQTT_Client()
    client.end() // 关闭连接
    console.log("服务器断开")
    wx.showToast({
      title: '服务器断开',
      icon: 'success',
    })
  }
});